package com.joymart.user.repo;

import com.joymart.user.model.BusinessRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public class BusinessRoleRepository {

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public List<String> findByBusinessRole(BusinessRole businessRole) {
        List<String> userIds = namedParameterJdbcTemplate.queryForList("select user_id from user_business_role where " +
                        "   business_role = :businessRole",
                Map.of("businessRole", businessRole.name()), String.class);
        return userIds;
    }


    public void deleteByUserId(String userId) {
        namedParameterJdbcTemplate.update("delete from user_business_role where user_id = :userId",
                new MapSqlParameterSource("userId", userId) );
    }

    public void insert(String userId, List<BusinessRole> businessRoles) {
        for (BusinessRole businessRole : businessRoles) {
           namedParameterJdbcTemplate.update(" insert into user_business_role (user_id, business_role) " +
                   " values(:userId, :businessRole)", Map.of("userId", userId, "businessRole", businessRole.name()));
        }
    }
    public List<BusinessRole> getBusinessRoles(String userId) {
        String sql = "select business_role from user_business_role where user_id=:userId";
        return namedParameterJdbcTemplate.query(sql, new MapSqlParameterSource("userId", userId),
                (rs, rowNum) -> BusinessRole.valueOf(rs.getString("business_role")));
    }

}
